package com.sicnu.cheer.leaugebar.eventmodule.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.sicnu.cheer.generalmodule.bean.EventBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.config.Constant;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.eventmodule.R;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;


public class EventDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private EventBean eventBean;
    private EventDetailActivity mThis;
    private TextView viewsTV;
    private TextView likesTV;
    private ImageView leagueLogoIV;
    private TextView launchUserTime;
    private ImageView attachImgIV;
    private TextView contentTV;
    private FloatingActionButton fabLike;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);
        mThis = this;
        initData();
        initView();
        afterView();
    }


    private void initData() {
        progressDialog=new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
        eventBean = (EventBean) getIntent().getSerializableExtra("event");
        if (eventBean.getOn()) {
            //如果活动弄正在进行中，则进入此页面，浏览量加1
            eventBean.increment("views");
            eventBean.update(mThis, eventBean.getObjectId(), new UpdateListener() {
                @Override
                public void onSuccess() {
                    eventBean.setViews(eventBean.getViews() + 1);
                    viewsTV.setText(eventBean.getViews() + "");
                }

                @Override
                public void onFailure(int i, String s) {
                }
            });
        }
    }

    private void initView() {
        ((TextView) findViewById(R.id.title)).setText(eventBean.getTitle());
        findViewById(R.id.back).setOnClickListener(this);
        viewsTV = ((TextView) findViewById(R.id.views_tv));
        likesTV = ((TextView) findViewById(R.id.likes_tv));
        findViewById(R.id.attend_people_num_ll).setOnClickListener(this);
        leagueLogoIV = ((ImageView) findViewById(R.id.league_logo_iv));
        launchUserTime = ((TextView) findViewById(R.id.launch_username_time));
        attachImgIV = ((ImageView) findViewById(R.id.attach_img_iv));
        contentTV = ((TextView) findViewById(R.id.content_tv));
        fabLike = ((FloatingActionButton) findViewById(R.id.fab_like));
        fabLike.setOnClickListener(this);
    }

    private void afterView() {
        viewsTV.setText(eventBean.getViews() + "");
        try {
            String likes = String.valueOf(eventBean.getLikesInt() );
            likesTV.setText(likes);
        } catch (Exception e) {
            likesTV.setText("0");
            e.printStackTrace();
        }
        Glide.with(mThis).load(eventBean.getLeague().getLogo()).placeholder(R.mipmap.default_logo).into(leagueLogoIV);

        launchUserTime.setText(eventBean.getAuthor().getNick() + " " + eventBean.getCreatedAt());
        Glide.with(mThis).load(eventBean.getImageUrl()).into(attachImgIV);
        contentTV.setText(eventBean.getContent());
        if (!eventBean.getOn()) {
            fabLike.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            onBackPressed();
        } else if (v.getId() == R.id.fab_like) {
            //用户点击参加按钮按钮，增加
            addAttendPeople();
        }else if (v.getId()==R.id.attend_people_num_ll){
            try {
                Integer likesInt = eventBean.getLikesInt();
                if (likesInt>0) {
                    Intent intent = new Intent(mThis, AttendPeopleListActivity.class);
                    intent.putExtra("event", eventBean);
                    startActivity(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户报名参加活动
     */
    private void addAttendPeople() {
        progressDialog.show();
        final MyUser user = MyUser.getCurrentUser(mThis, MyUser.class);
        BmobQuery<MyUser> query=new BmobQuery<>();
        query.addWhereRelatedTo("likes",new BmobPointer(eventBean));
        query.findObjects(mThis, new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                if (list.size()>0){
                    boolean exist=false;
                    for (MyUser u :list) {
                        if (u.getObjectId().equals(user.getObjectId())){
                            progressDialog.dismiss();
                            //如果存在这个用户，则不进行添加用户参加关系
                            UIHelper.ToastMessage(mThis,"您已经参加过此活动了");
                            fabLike.setVisibility(View.GONE);
                            exist=true;
                            break;
                        }
                    }
                    if (!exist){
                        addRelation(user);
                    }
                }else {
                   addRelation(user);
                }
            }

            @Override
            public void onError(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"参加失败："+s);
            }
        });

    }

    /**
     * 将用户加入参加活动的名单中
     * @param user
     */
    private void addRelation(MyUser user) {
        BmobRelation newRelation = new BmobRelation();
        newRelation.add(user);
        eventBean.setLikes(newRelation);
        eventBean.update(mThis, eventBean.getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                incrementLikes();
            }

            @Override
            public void onFailure(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"参加失败："+s);
            }
        });
    }

    /**
     * 喜欢数自增1
     */
    private void incrementLikes() {
        //用户点击点赞按钮，增加
        eventBean.increment("likesInt");
        eventBean.update(mThis, eventBean.getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                progressDialog.dismiss();
                eventBean.setLikesInt(eventBean.getLikesInt()+1);
                likesTV.setText(eventBean.getLikesInt()+"");
                UIHelper.ToastMessage(mThis,"参加成功");
            }

            @Override
            public void onFailure(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"参加失败："+s);
            }
        });
    }
}
